🎯 Objectives of the Topic
• Master Files: Get hands-on with opening, reading, writing, and closing files in Python!
• Handle Errors Like a Pro: Learn how to catch and manage errors, ensuring your code runs smoothly even when things don’t go as planned.
đź“„ What is File Handling?
File Handling in Python is the ability to perform various operations on files, like reading from and writing to them. Files provide persistent storage, unlike variables which lose their values when a program ends.
File handling in Python allows you to:
1. Open files in different modes (read, write, append).
2. Read and write data in a variety of formats.
3. Close files to free up system resources.
Python’s built-in open() function is at the heart of this process, making your programs more robust, flexible, and useful.
📝 File Operations in Python
Let’s start with the basics of file handling! (1.5 hours)
• Opening Files
Use Python’s open() function to access a file.
Syntax: open(filename, mode), where:
• filename: The name of the file you want to work with.
• mode: The mode you want to open the file in.
Common modes:
• 'r': Read mode
• 'w': Write mode (creates new file or overwrites)
• 'a': Append mode (adds content without deleting existing data)
• 'rb', 'wb': Binary modes for non-text files
Example:
file = open("example.txt", "r") # Opens the file in read mode
• Reading Files
Python provides multiple ways to read file contents:
• .read(): Reads the entire file
• .readline(): Reads a single line at a time
• .readlines(): Reads all lines and returns a list
Example:
with open("example.txt", "r") as file:
data = file.read()
print(data)
• Writing & Appending to Files
Writing is essential for saving data, like storing a user’s progress or keeping a record.
write() overwrites content, while append() adds new content without deleting.
Example:
with open("output.txt", "w") as file:
file.write("Hello, Python!")
• Closing Files
Files should be closed after processing to release system resources.
Using Python’s with statement automatically handles closing:
with open("example.txt", "r") as file:
data = file.read()
# File is automatically closed after this block